package com.pkk.components.encryption.factory;

import java.util.Optional;
import org.jasypt.util.text.BasicTextEncryptor;

/**
 * @description: 密码加密工厂
 * @author: peikunkun
 * @create: 2019-07-30 18:30
 **/
public class JasyptEncryFactory implements JasyptEncryFactoryInterface {

  /**
   * 加密盐
   */
  private String salt;
  /**
   * 加密操作类
   */
  BasicTextEncryptor textEncryptor = new BasicTextEncryptor();


  /**
   * @Description: 使用说明
   * @Param: []
   * @return: void
   * @Author: peikunkun
   * @Date: 2019/7/30 0030 下午 6:37
   */
  @Override
  public void readme() {
    toReadme();
  }

  /**
   * @Description: 使用说明
   * @Param: []
   * @return: void
   * @Author: peikunkun
   * @Date: 2019/7/30 0030 下午 6:37
   */
  public static void toReadme() {
    StringBuilder readme = new StringBuilder();
    readme.append("-----------------------------------------------------------------------------------\n");
    readme.append("①:getInstance获取实例\n");
    readme.append("②:getInstance().readme()使用说明\n");
    readme.append("③:getInstance().encode()进行加密\n");
    readme.append("④:getInstance().decode()进行解密\n");
    readme.append("⑥:java -jar -Djasypt.encryptor.password=G0CvDz7oJn6 xxx.jar(启动时把盐放到环境中去)\n");
    readme.append("⑦:打开/etc/profile文件\n");
    readme.append("⑦:打开/etc/profile文件\n");
    readme.append("vim /etc/profile\n");
    readme.append("文件末尾插入\n");
    readme.append("export JASYPT_PASSWORD = G0CvDz7oJn6\n");
    readme.append("编译 \n");
    readme.append("source /etc/profile\n");
    readme.append("运行 \n");
    readme.append("java -jar -Djasypt.encryptor.password=${JASYPT_PASSWORD} xxx.jar\n");
    readme.append("⑦:将生成的加密串配置ENC(加密串)到application.properties中\n");
    readme.append("如:spring.datasource.password=ENC(6eaMh/RX5oXUVca9ignvtg==)\n");
    readme.append("-----------------------------------------------------------------------------------\n");
    System.out.println(readme.toString());
  }


  /**
   * @Description:获取加密的抽象工厂
   * @Param: [salt:盐]
   * @return: com.pkk.components.encryption.factory.JasyptEncryFactoryInterface
   * @Author: peikunkun
   * @Date: 2019/7/30 0030 下午 6:37
   */
  @Override
  public JasyptEncryFactoryInterface getInstance(String salt) {
    Optional.ofNullable(salt).orElseThrow(() -> new IllegalArgumentException("加密盐非法"));
    this.salt = salt;
    //加密所需的salt(盐)
    textEncryptor.setPassword(salt);
    return this;
  }

  /**
   * @Description:进行编码
   * @Param: [encode]
   * @return: java.lang.String
   * @Author: peikunkun
   * @Date: 2019/7/30 0030 下午 6:54
   */
  @Override
  public String encode(String encode) {
    //要加密的数据（数据库的用户名或密码）
    return textEncryptor.encrypt(encode);
  }

  /**
   * @Description:进行编码
   * @Param: [encode]
   * @return: java.lang.String
   * @Author: peikunkun
   * @Date: 2019/7/30 0030 下午 6:54
   */
  @Override
  public String decode(String decode) {
    return textEncryptor.decrypt(decode);
  }
}
